package org.example.jdbcexamples.mapper;

import org.example.jdbcexamples.dox.Address;
import org.example.jdbcexamples.dto.UserAddress;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class UserAddressResultSetExtractor implements ResultSetExtractor<UserAddress> {
    @Override
    public UserAddress extractData(ResultSet rs) throws SQLException, DataAccessException {
        List<Address> addresses = new ArrayList<>();
        UserAddress.UserAddressBuilder userAddressBuilder= UserAddress.builder();
        while(rs.next()){
            userAddressBuilder.id(rs.getString("user_id"));
            userAddressBuilder.name(rs.getString("name"));
            userAddressBuilder.createTime(rs.getObject("u.create_time", LocalDateTime.class));
            userAddressBuilder.updateTime(rs.getObject("u.update_time", LocalDateTime.class));
            Address a = Address.builder().id(rs.getString("a.id")).userId(rs.getString("user_id")).detail(rs.getString("detail")).createTime(rs.getObject("a.create_time", LocalDateTime.class)).updateTime(rs.getObject("a.update_time", LocalDateTime.class)).build();
            addresses.add(a);
        }
        UserAddress userAddress = userAddressBuilder.addresses(addresses).build();
        return userAddress;
    }
}
